package club.gskj.gulimall.ware.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import sun.text.normalizer.UCharacterProperty;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class MyRabbitConfig {

    /**
     * 使用 Jackson2JsonMessageConverter 将message消息转换为 Json格式。
     */
    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    /**
     * 库存交换机
     */
    @Bean
    public Exchange stockEventExchange() {
        // String name, boolean durable, boolean autoDelete, Map<String, Object> arguments
        TopicExchange topicExchange = new TopicExchange("stock-event-exchange", true, false);
        return topicExchange;
    }

    /***
     * 容器中的这些组件都会自动创建(MQ中没有的话)
     *  死信队列
     *
     *  一旦创建好队列，MQ中只要有，即使后创建的相同队列的一些属性改变，mq的对应也不会改变
     */
    @Bean
    public Queue stockDelayQueue() {
        // 设置属性
        Map<String, Object> arguments = new HashMap<>();

        arguments.put("x-dead-letter-exchange", "stock-event-exchange");
        arguments.put("x-dead-letter-routing-key", "stock.release");
        arguments.put("x-message-ttl", 120000);

        Queue queue = new Queue("stock.delay.queue", true, false, false, arguments);
        return queue;
    }

    /**
     * 普通队列
     */
    @Bean
    public Queue stockReleaseStockQueue() {
        Queue queue = new Queue("stock.release.stock.queue", true, false, false);
        return queue;
    }

    /**
     * 绑定规则1
     */
    @Bean
    public Binding stockLockedBinding() {
        // Binding(String destination, Binding.DestinationType destinationType, String exchange, String routingKey, Map<String, Object> arguments)

        Binding binding = new Binding("stock.delay.queue",
                Binding.DestinationType.QUEUE,
                "stock-event-exchange",
                "stock.locked",
                null);
        return binding;
    }

    /**
     * 绑定规则2
     */
    @Bean
    public Binding stockReleaseBinding() {
        Binding binding = new Binding("stock.release.stock.queue",
                Binding.DestinationType.QUEUE,
                "stock-event-exchange",
                "stock.release.#",
                null);
        return binding;
    }

    /**
     * 监听队列
     *
     * @param message
     */
//    @RabbitListener(queues = {"stock.release.stock.queue"})
//    public void listener(Message message) {
//
//    }
}
